<template>
    <view class="page">
        <!-- 数据详情 -->

        <view class="item">
            <view v-if="isLogin"
                ><view class="itemBox flex_wrap">
                    <text class="total">配送方式</text>
                    <view class="flex_wrap">
                        <view
                            :class="[
                                listIndex == i ? 'typeBox active' : 'typeBox',
                            ]"
                            v-for="(item, i) in list"
                            :key="i"
                            @click="listIndex = i"
                            ><u-icon
                                :name="listIndex === i ? item.icon1 : item.icon"
                            ></u-icon>
                            <text>{{ item.title }}</text></view
                        >
                    </view>
                </view>
                <view class="itemBox" v-show="!listIndex">
                    <!-- 地址 -->
                    <chooseAddress
                        ref="childRef"
                        @changeAddress="changeAddress"
                    ></chooseAddress>
                </view>
                <view class="itemBox" v-show="listIndex">
                    <u-form
                        labelPosition="top"
                        ref="uForm"
                        :model="loginForm"
                        :labelStyle="labelStyle"
                    >
                        <u-form-item label="姓名" prop="receiveName">
                            <view class="formInput">
                                <u-input
                                    placeholder="请输入名字"
                                    v-model="loginForm.receiveName"
                                    clearable
                                    border="none"
                                    fontSize="26rpx"
                                    color="#333"
                                    customStyle="background:#F3F3F3;border-radius: 6px"
                                ></u-input>
                            </view>
                        </u-form-item>

                        <u-form-item
                            label="手机号"
                            labelWidth="100"
                            prop="receivePhone"
                        >
                            <view class="formInput">
                                <u-input
                                    placeholder="请输入手机号"
                                    border="none"
                                    fontSize="26rpx"
                                    color="#333"
                                    v-model="loginForm.receivePhone"
                                    clearable
                                />
                            </view>
                        </u-form-item>
                    </u-form>
                </view>

                <u-gap height="7" bgColor="#F5F5F5"></u-gap
            ></view>
            <view
                class="item_detail flex_wrap row_between"
                @click="toProductDetail"
            >
                <image :src="currentProduct.thumbnail" mode="aspectFill" />
                <view>
                    <text class="total">{{
                        orderMessage.goodsName || "--"
                    }}</text>
                    <view
                        class="detail_tt flex_wrap"
                        v-if="orderMessage.skuInfo"
                    >
                        <text>{{ orderMessage.skuInfo }}</text>
                    </view>
                    <u-gap height="26rpx" />
                    <view v-if="orderMessage.unitPrice">
                        <text
                            style="
                                color: #ff0000;
                                font-size: 20rpx;
                                font-weight: bold;
                            "
                            >￥</text
                        >
                        <text
                            style="
                                color: #ff0000;
                                font-size: 40rpx;
                                font-weight: bolder;
                            "
                            >{{
                                formatDecimal(
                                    numDiv(orderMessage.unitPrice, 100)
                                )
                            }}</text
                        >
                    </view>
                </view>
            </view>
            <view class="goodsNum">
                <view class="goodsNum_item">商品数量</view>
                <view class="num" v-if="getPrice">
                    <u-number-box
                        v-model="productCount"
                        integer
                        :min="orderMessage.quantity"
                    ></u-number-box>
                </view>
				<view class="num" v-else>{{'x'+productCount}}</view>
            </view>
            <u-gap height="7" bgColor="#F5F5F5"></u-gap>
        </view>
        <view class="payMode">
            <view class="payMode_title">支付方式</view>
            <view
                :class="item.class"
                v-for="(item, index) in payWays"
                :key="item.type"
                @click="chooseWeixin(index)"
            >
                <view style="display: flex">
                    <image
                        style="width: 64rpx; height: 64rpx; margin-right: 10rpx"
                        :src="item.icon"
                    />
                    <u-text :text="item.text" />
                </view>
                <view>
                    <image
                        v-if="item.checked"
                        style="
                            width: 56rpx;
                            height: 56rpx;
                            position: absolute;
                            right: 30rpx;
                        "
                        src="/pages_shop1/static/img/order/choose.png"
                    ></image>
                    <image
                        v-else
                        style="
                            width: 56rpx;
                            height: 56rpx;
                            position: absolute;
                            right: 30rpx;
                        "
                        src="/pages_shop1/static/img/order/notChoose.png"
                    ></image>
                </view>
            </view>
        </view>
        <view class="page_bottom safeAreaBottom">
            <view
                class="total_price"
                style="
                    line-height: 56rpx;
                    color: #ff0303;
                    font-size: 40rpx;
                    font-weight: bolder;
                "
                v-if="orderMessage"
            >
                ￥{{ getPrice }}
            </view>
            <u-button
                type="primary"
                @click="toPay"
                customStyle="width:216rpx;height:56rpx;border-radius:28rpx;line-height:100rpx;position:absolute;right:28rpx;backgroundColor:#588BF3"
                text="立即结算"
                :disabled="payButtonLoading"
            />
        </view>
        
        <!-- 二维码弹窗组件 -->
        <qrcode-popup
          :show="showQRCodePopup"
          title="请前往小程序支付"
          @close="handleQRCodeClose"
          @save-success="handleQRCodeSaveSuccess"
          @save-fail="handleQRCodeSaveFail"
        />
    </view>
</template>

<script>
import { confirmOrder, getActiveGoodsById ,getRememberHealthManagered } from "@/api/order.js";
import { getGoodsDetailAuth } from "@/api/shop.js";
import { appIdCard } from "@/api/card";
import {
    numAdd,
    numSub,
    numMulti,
    numDiv,
} from "@/js_sdk/nl-precisionNum/precisionNum.js";
import { formatDecimal } from "@/utils/index.js";
import { mapGetters } from "vuex";
import chooseAddress from "../../components/changeAddress";
import caches from "@/config/caches.js";
import QRCodePopup from '@/components/qrcode-popup/qrcode-popup.vue';

export default {
    components: {
        chooseAddress,
        QRCodePopup,
    },
    data() {
        return {
            numAdd,
            numSub,
            numMulti,
            numDiv,
            formatDecimal: formatDecimal,
            payButtonLoading: false,
            time: 30,
            payCode: "",
            show: false,
            orderMessage: {},
            currentProduct: {},
            tenantId: "",
            productCount: 0,
            showQRCodePopup: false,
            appLogoImage: "https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2023/10/23/0e6265fd99fa49a9bacf3791420d6de6.png", // 使用app logo作为临时二维码图片
            payWay: 1, //1:'微信支付' || 2:'积分支付'
            consigneeId: "",
            promoteSalesmanId: "",
            payWays: [
                {
                    type: 1,
                    text: "微信支付",
                    checked: true,
                    icon: "/pages_shop1/static/img/order/weixin.png",
                    class: "weixin",
                },
                // {
                // 	type: 1,
                // 	text: '积分支付',
                // 	checked: false,
                // 	icon: '/pages_shop1/static/img/order/jifen.png',
                // 	class: 'jifen'
                // }
            ],
            list: [
                {
                    title: "快递",
                    icon: "https://test-health-s.oss-cn-hangzhou.aliyuncs.com/report/order/2023/12/06/1e905b8d36d94a9784312859384aec73.png",
                    icon1: " https://test-health-s.oss-cn-hangzhou.aliyuncs.com/report/order/2023/12/06/bcea68b639784347aa84de33b43eb9e8.png",
                },
                {
                    title: "自提",
                    icon: "https://test-health-s.oss-cn-hangzhou.aliyuncs.com/report/order/2023/12/06/a38f3fc8053949deb02b86a733c925a4.png",
                    icon1: "https://test-health-s.oss-cn-hangzhou.aliyuncs.com/report/order/2023/12/06/557b096fc54c4db0a0313a03f8bc2d78.png",
                },
            ],
            listIndex: 0,
            loginFormRules: {
                receiveName: [
                    {
                        type: "string",
                        required: true,
                        message: "请填写姓名",
                        trigger: ["blur", "change"],
                    },
                ],
                receivePhone: [
                    {
                        required: true,
                        message: "请输入手机号",
                        trigger: ["change", "blur"],
                    },
                    {
                        validator: (rule, value, callback) => {
                            return uni.$u.test.mobile(value);
                        },
                        message: "手机号码不正确",
                        trigger: ["change", "blur"],
                    },
                ],
            },
            loginForm: {
                receivePhone: "",
                receiveName: "",
            },
        };
    },
    onReady() {
        this.isLogin && this.$refs.uForm.setRules(this.loginFormRules);
    },
    computed: {
        ...mapGetters(["userInfo", "isLogin", "phone"]),
        getPrice() {
            let currentMoney = 0;
            currentMoney =
                this.orderMessage.unitPrice &&
                formatDecimal(
                    numMulti(
                        numDiv(this.orderMessage.unitPrice, 100),
                        this.productCount
                    )
                );
            return currentMoney;
        },
    },
    beforeDestroy() {
        if (this.isLogin) {
            uni.removeStorageSync("loginBackUrl");
            uni.removeStorageSync("loginBackUrlOption");
        }
    },
    onLoad(options) {
        const activeGoodsId = options.scene;
        if (options.promoteSalesmanId)
            this.promoteSalesmanId = options.promoteSalesmanId;
        getActiveGoodsById(activeGoodsId).then((res) => {
            if (res.code === 200 && res.data) {
                this.orderMessage = res.data;
                this.productCount = res.data.quantity;
                this.getGoodDetail(this.orderMessage.goodsId);
            }
        });
        console.log(
            uni.getStorageSync(caches.ISLOGIN),
            "this.isLogin :>> ",
            this.isLogin
        );
        this.isLogin && this.$store.dispatch("GET_ADDRESS_LIST");
        this.isLogin && (this.loginForm.receivePhone = this.phone);
        if (!this.isLogin) {
            let pages = getCurrentPages(); // 获取栈实例
            let currentRoute = pages[pages.length - 1].route; // 获取当前页面路由
            uni.setStorageSync("loginBackUrl", "/" + currentRoute);
            uni.setStorageSync("loginBackUrlOption", options);
        }
    },
    methods: {
        toProductDetail() {
            uni.navigateTo({
                url: `/pages_shop1/goods/index?id=${this.orderMessage.goodsId}&hideBtn=true`,
            });
        },
        changeList(i) {},
        changeAddress(id) {
            this.consigneeId = id;
        },
        chooseWeixin(index) {
            this.payWays = this.payWays.map((item, payWayIndex) => {
                item.checked = false;
                if (payWayIndex === index) {
                    item.checked = true;
                    this.payWay = item.type;
                }
                return item;
            });
        },
        toPay() {
            if (!this.isLogin)
                return uni.navigateTo({ url: "/pages/user/phone/indexApp" });
            this.listIndex &&
                this.$refs.uForm.validate().then(async () => {
                    await this.pay();
                });
            !this.listIndex && this.pay();
        },
        async pay() {
            // 显示二维码弹窗，引导用户到小程序支付
            this.showQRCodePopup = true;
            return;
            
            // this.payButtonLoading = true;
			const that = this;
            let data;
            let params = {
                consigneeId: this.consigneeId, //地址id
                goodsCount: this.productCount,
                goodsId: this.orderMessage.goodsId,
                goodsName: this.orderMessage.goodsName,
                orderAmount: this.getPrice,
                orderPaymentType: this.payWay,
                activityId: this.orderMessage.id,
                orderReceiveType: this.listIndex === 0 ? 1 : 2, //1邮寄，2自提'
            };
            // 自提
            this.listIndex && (params = { ...params, ...this.loginForm });
            // 存在 skuId
            this.orderMessage.skuId &&
                (params.goodsSkuId = this.orderMessage.skuId);
            if (this.promoteSalesmanId)
                params.promoteSalesmanId = this.promoteSalesmanId;
            const result = await confirmOrder(params);
            data = result.data;
            // 0 元支付 阻止微信支付
            console.log("object :>> datadatadata", data);
            if (data.outTradeNo && !data.appId && !data.packageValue) {
                uni.$u.route({
                    type: "reLaunch",
                    url: "pages_shop1/pay/payResult/index",
                    params: {
                        status: "success",
                        orderNum: data.outTradeNo,
                    },
                });
                return;
            }
            uni.requestPayment({
                provider: "wxpay",
                timeStamp: data.timeStamp,
                nonceStr: data.nonceStr,
                package: data.packageValue,
                signType: "MD5",
                paySign: data.paySign,
                success: function (res) {
                    if (res.errMsg === "requestPayment:ok") {
                        // uni.$u.route({
                        //     type: "redirectTo",
                        //     url: "pages_shop1/pay/payResult/index",
                        //     params: {
                        //         status: "success",
                        //         orderNum: data.outTradeNo,
                        //     },
                        // });
						that.getIsWeChat()
                    }
                },
                fail: function (err) {
                    console.log("fail:" + JSON.stringify(err));
                    if (err.errMsg === "requestPayment:fail cancel") {
                        uni.$u.route({
                            type: "redirectTo",
                            url: "pages_shop1/pay/payResult/index",
                            params: {
                                status: "fail",
                                orderNum: data.outTradeNo,
                            },
                        });
                    }
                },
            });
        },
		getIsWeChat(){
			getRememberHealthManagered().then((res) => {
				if (res.code === 200 && res.data) {
					uni.$u.route({
						type: "redirectTo",
						url: "pages_shop1/addWeChat/index",
						params: {
							wcName: res.data.nickName,
							wcImgUrl:res.data.wechatCpQrCode
						},
					});
				}else{
					uni.$u.route({
						type: "redirectTo",
						url: "pages_shop1/order/order_list/index",
					});
				}
			});
		},
        async getGoodDetail(id) {
            const result = await getGoodsDetailAuth(id);
            this.currentProduct = result.data || {};
        },
        showType() {
            wx.setNavigationBarColor({
                frontColor: "#000000",
                backgroundColor: "#ffffff",
            });
        },
        open() {
            this.show = true;
            this.time = 30;
            clearInterval();
            setInterval(() => {
                this.time--;
                if (this.time <= 0) {
                    this.close();
                }
            }, 1000);
        },
        close() {
            this.show = false;
            this.payCode = "";
        },
        
        // 二维码弹窗相关方法
        handleQRCodeClose() {
            this.showQRCodePopup = false;
        },
        
        handleQRCodeSaveSuccess() {
            console.log('二维码保存成功');
        },
        
        handleQRCodeSaveFail(error) {
            console.log('二维码保存失败:', error);
        },
    },
};
</script>

<style lang="scss">
.page {
    background-color: #ffffff;
    height: 100vh;
}
.itemBox {
    padding: 40rpx 20rpx;
    border-bottom: 2rpx solid #f3f3f3;
}
.item_detail {
    border-bottom: 2rpx solid #f3f3f3;
    padding: 26rpx 24rpx 20rpx;

    image {
        width: 220rpx;
        height: 220rpx;
    }
}

.total {
    display: block;
    width: 448rpx;
    word-break: break-all;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2; /* 这里是超出几行省略 */
    overflow: hidden;
    font-weight: bold;
    font-size: 30rpx;
    color: #333;
}

.detail_tt {
    margin-top: 20rpx;
    font-size: 26rpx;
    color: #666666;

    text {
        margin-right: 10rpx;
    }
}

.goodsNum {
    padding: 24rpx 28rpx 28rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.goodsNum_item {
    font-size: 32rpx;
    font-weight: bolder;
}

.num {
    font-size: 24rpx;
    color: #999999;
}

.payMode {
    padding: 40rpx 28rpx 0;
}

.payMode_title {
    font-size: 32rpx;
    font-weight: bolder;
    margin-bottom: 28rpx;
}

.weixin {
    display: flex;
    margin-bottom: 40rpx;
}

.jifen {
    display: flex;
}

.page_bottom {
    width: 750rpx;
    min-height: 100rpx;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    justify-content: space-between;
    background: #ffffff;
    box-shadow: 4px -3px 4px -1px rgba(0, 0, 0, 0.25);
    padding: 22rpx 28rpx;
}

.connect {
    display: flex;
    line-height: 72rpx;
}

.connect_icon {
    width: 32rpx;
    height: 32rpx;
    vertical-align: middle;
}

.connect_text {
    line-height: 72rpx;
}

.pay_box {
    padding: 24rpx 30rpx 44rpx 48rpx;
}

.pay_title {
    display: flex;
    justify-content: center;
}

.title_text {
    font-size: 40rpx;
    font-weight: bold;
    margin-left: 85rpx;
}

.title_time {
    font-size: 24rpx;
    color: #999999;
    margin-left: 10rpx;
    margin-top: 16rpx;
}

.pay_price {
    width: 196rpx;
    height: 56rpx;
    text-align: center;
    margin: 16rpx auto;
    font-size: 40rpx;
    line-height: 56rpx;
    font-weight: bold;
    color: #ff0000;
}

.pay_remainderIntegral {
    text-align: center;
    width: 240rpx;
    height: 34rpx;
    margin: 0 auto;
    line-height: 34rpx;
    margin-top: 28rpx;
    font-size: 24rpx;
    color: #999999;
}

.pay_code {
    margin-top: 50rpx;
    display: flex;
    justify-content: center;
}

.u-code-input__item {
    background-color: #ededed;
    border-radius: 8rpx;
}
.typeBox {
    font-size: 28rpx;
    color: #588bf3;
    border-radius: 8rpx 8rpx 8rpx 8rpx;
    border: 2rpx solid #588bf3;
    width: 140rpx;
    height: 46rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    box-sizing: border-box;
    margin: 0 10rpx;
}
.active {
    background-color: #588bf3;
    border: 2rpx solid #588bf3;
    color: #ffffff;
}
.formInput,
.formInput_t {
    height: 80rpx;
    background: #f3f3f3;
    border-radius: 12rpx;
    display: flex;
    align-items: center;
    padding: 0 20rpx;
}

.formInput_t {
    width: 460rpx;
}
</style>
